<script lang="ts">
export const pageDefault = {
  page: 1,
  limit: 10,
  sizes: [10, 20, 50],
  background: true
}

export interface PostItem {
  needPage: number;
  page: number;
  limit: number;
  keyword_type: number | string;
  keyword: string;
  biz_id: number | string;
  brand: Array<number>;
  shop: Array<number>;
  city: Array<number>;
  add_dept_id: Array<number>;
  add_user_id: Array<number>;
  order_date_id_dept: Array<number>;
  order_date_id_user: Array<number>;
  cus_type: string | number;
  sex: string | number;
  status: string | number;
  is_undetermined: string | number;
  date: [string, string];
}


</script>
<script setup lang="ts">

import {RefreshLeft, Search} from "@element-plus/icons-vue";
import {h, onBeforeMount, reactive, ref, shallowRef, watch} from "vue";

import {useCloned} from "@vueuse/core"
import {
  bizBrandFromStore,
  bizDeptEmployeeFromStore,
  bizDeptFromStore,
  bizFromStore,
  bizShopCityFromStore,
  bizShopFromStore,
  formatDateYmd,
  todayYMD
} from "@/dt-lib/help/fun.ts";


import type {EmployeeVO, SelectItemVO, ShopShowVO, ShopVO, DeptVO} from "@/dt-lib/help/TypeVos.ts"

const searchData = reactive<PostItem>({
  needPage: 1,
  page: pageDefault.page,
  limit: pageDefault.limit,
  keyword_type: '1',
  keyword: '',
  biz_id: 0,
  brand: [],
  shop: [],
  city: [],
  add_dept_id: [],
  add_user_id: [],
  order_date_id_dept: [],
  order_date_id_user: [],
  cus_type: '',
  sex: '',
  status: '',
  is_undetermined: 2,
  date: [todayYMD(), todayYMD()]
})

const Props = defineProps({
  btLoading: {
    type: Boolean,
    required: true,
    default: false
  },
})

//
// const Props = defineProps({
//   btLoading: {
//     type: Boolean,
//     required: true,
//     default: false
//   },
//   searchData: {
//     type: Object as PropType<PostItem>,
//     required: false,
//     default: () => (
//         {
//           needPage: true,
//           keyword_type: '1',
//           keyword: '',
//           biz_id: 0,
//           brand: [],
//           shop: [],
//           city: [],
//           add_dept_id: [],
//           add_user_id: [],
//           order_date_id_dept: [],
//           order_date_id_user: [],
//           cus_type: '',
//           sex: '',
//           status: '',
//           is_undetermined: 2,
//           date: [todayYMD(), todayYMD()]
//         }
//     )
//   },
//
// })


const searchFormData = reactive<PostItem>(useCloned<PostItem>(searchData).cloned.value);

const manageShopCity = ref<SelectItemVO[]>([])
const manageShop = ref<ShopShowVO[]>([])
const manageBiz = ref<SelectItemVO[]>([])
const manageBrand = ref<SelectItemVO[]>([])
const manageDept = ref<DeptVO[]>([])
const manageDeptIds = ref<number[]>([])
const manageDeptEmployee = ref<EmployeeVO[]>([])
const manageDeptOrderEmployee = ref<EmployeeVO[]>([])


const customPrefix = shallowRef({
  render() {
    return h('span', '')
  },
})

onBeforeMount(() => {
  //事业部
  manageBiz.value = bizFromStore()
  searchFormData.biz_id = manageBiz.value[0]['id']

  // console.log(manageDept.value)
  // console.log(manageDeptIds.value)
})

const statusOptions = [
  {
    value: '1',
    label: '预约中',
  },
  {
    value: '2',
    label: '已开单',
  },
  {
    value: '6',
    label: '流失中',
  },
  {
    value: '7',
    label: '已流失',
  }
]

//预约/排店人
const handleDeptEmployee = (deptIds: number[], deptType: string[]) => {

  let employee: EmployeeVO[] = []

  if (searchFormData.biz_id) {

    if (deptIds.length == 0) {
      deptIds = manageDeptIds.value
    }

    employee = bizDeptEmployeeFromStore(searchFormData.biz_id, deptIds)
  }

  employee = employee ? employee.sort((a, b) => a.status - b.status) : []


  if (deptType.includes('add')) {
    manageDeptEmployee.value = employee
  }

  if (deptType.includes('order')) {
    manageDeptOrderEmployee.value = employee
  }

}

watch(() => searchFormData.biz_id, (newVal) => {

  const bizShop = bizShopFromStore(newVal);
  const bizShopShow: ShopShowVO[] = []
  if (bizShop.length > 0) {
    bizShop.forEach((item: ShopVO) => {
      bizShopShow.push({...item, show: 1})
    })
  }

  manageShop.value = bizShopShow

  //城市
  manageShopCity.value = bizShopCityFromStore(newVal)
  //品牌
  manageBrand.value = bizBrandFromStore(newVal)

  //部门
  const bizDeptObject = bizDeptFromStore(newVal, '1,2,3,8') // 1售前，2售中，3售后，8大客户
  manageDept.value = bizDeptObject.tree
  manageDeptIds.value = bizDeptObject.ids

  searchFormData.brand = []
  searchFormData.city = []
  searchFormData.shop = []
  searchFormData.add_dept_id = []
  searchFormData.add_user_id = []
  searchFormData.order_date_id_dept = []
  searchFormData.order_date_id_user = []

  handleDeptEmployee(manageDeptIds.value, ['add', 'order'])

})


watch(() => searchFormData.add_dept_id, (newVal) => {

  let deptIdArr: number[] = []
  newVal.forEach((item: number[]) => {
    deptIdArr = [...deptIdArr, ...item]
  })

  const deptIds = [...new Set(deptIdArr)]

  handleDeptEmployee(deptIds, ['add'])

})

watch(() => searchFormData.order_date_id_dept, (newVal) => {

  let deptIdArr: number[] = []
  newVal.forEach((item: number[]) => {
    deptIdArr = [...deptIdArr, ...item]
  })

  const deptIds = [...new Set(deptIdArr)]

  handleDeptEmployee(deptIds, ['order'])

})

watch(() => searchFormData.city, (newVal) => {

  if (newVal.length > 0) {
    manageShop.value.forEach((item) => {
      const isFound = newVal.some(element => element == item['city']);
      item.show = isFound ? 1 : 0;
    })
  } else {
    manageShop.value.forEach((item) => {
      item.show = 1;
    })
  }

})


const emit = defineEmits(['search']);

const onSearchForm = () => {
  onSearch(searchFormData.limit, pageDefault.page)
};

const onSearch = (limit: number, page: number) => {
  searchFormData.page = page
  searchFormData.limit = limit
  emit('search', searchFormData)
};

const resetSearch = () => {

  searchFormData.biz_id = manageBiz.value[0]['id']
  searchFormData.page = pageDefault.page
  // 分页 - 每页数不设置为默认值
  // searchFormData.limit = pageDefault.limit
  searchFormData.keyword_type = '1'
  searchFormData.keyword = ''
  searchFormData.brand = []
  searchFormData.shop = []
  searchFormData.city = []
  searchFormData.add_dept_id = []
  searchFormData.add_user_id = []
  searchFormData.order_date_id_dept = []
  searchFormData.order_date_id_user = []
  searchFormData.cus_type = ''
  searchFormData.sex = ''
  searchFormData.status = ''
  searchFormData.is_undetermined = 2
  searchFormData.date = [todayYMD(), todayYMD()]

  onSearchForm()

}


defineExpose({
  onSearch
});


</script>

<template>
  <el-row :gutter="10" style="width: 100%;">
    <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
      <el-form-item prop="name">
        <MyFormItem title="事业部" size="large">
          <el-select v-model="searchFormData.biz_id" placeholder="Select">
            <el-option
                v-for="item in manageBiz"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </MyFormItem>
      </el-form-item>
    </el-col>
    <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
      <el-form-item prop="name">
        <MyFormItem title="品牌" size="large">
          <el-select

              filterable
              clearable
              multiple
              collapse-tags
              collapse-tags-tooltip
              v-model="searchFormData.brand"
              placeholder="请选择">
            <el-option
                v-for="item in manageBrand"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </MyFormItem>
      </el-form-item>
    </el-col>

    <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
      <el-form-item prop="city">
        <MyFormItem title="门店城市" size="large">
          <el-select
              filterable
              clearable
              multiple
              collapse-tags
              collapse-tags-tooltip
              v-model="searchFormData.city"
              placeholder="请选择"
          >
            <el-option
                v-for="item in manageShopCity"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </MyFormItem>
      </el-form-item>
    </el-col>
    <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
      <el-form-item prop="city">
        <MyFormItem title="门店" size="large">
          <el-select
              filterable
              clearable
              multiple
              collapse-tags
              collapse-tags-tooltip
              v-model="searchFormData.shop"
              placeholder="请选择"
          >
            <el-option
                v-for="item in manageShop"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                v-show="item.show ===1"
            />
          </el-select>
        </MyFormItem>
      </el-form-item>
    </el-col>
    <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
      <el-form-item prop="city">
        <MyFormItem title="预约部门" size="large">
          <el-cascader
              v-model="searchFormData.add_dept_id"
              :options="manageDept"
              :props="{ multiple: true,value:'id',label:'name',children:'children' }"
              collapse-tags
              collapse-tags-tooltip
              clearable
          />
        </MyFormItem>
      </el-form-item>
    </el-col>

    <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
      <el-form-item prop="city">
        <MyFormItem title="预约人" size="large">
          <el-select-v2
              v-model="searchFormData.add_user_id"
              :options="manageDeptEmployee"
              :props="{label: 'name', value: 'id'}"
              placeholder="请选择"
              filterable
              clearable
              multiple
              collapse-tags
              collapse-tags-tooltip
          >
            <template #default="{ item }">

              <span style="margin-right: 8px">{{ item.name }}</span>
              <span style="color: var(--el-text-color-secondary); font-size: 12px" v-if="item.status!=1">离职于<template
                  v-if="item.quit_addtime>0">{{ formatDateYmd(item.quit_addtime, false) }}</template></span>

            </template>
          </el-select-v2>
        </MyFormItem>
      </el-form-item>
    </el-col>


    <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
      <el-form-item prop="city">
        <MyFormItem title="排店部门" size="large">
          <el-cascader
              v-model="searchFormData.order_date_id_dept"
              :options="manageDept"
              :props="{ multiple: true,value:'id',label:'name',children:'children' }"
              collapse-tags
              collapse-tags-tooltip
              clearable
          />
        </MyFormItem>
      </el-form-item>
    </el-col>

    <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
      <el-form-item prop="city">
        <MyFormItem title="排店人" size="large">
          <el-select-v2
              v-model="searchFormData.order_date_id_user"
              :options="manageDeptOrderEmployee"
              :props="{
                        label: 'name',
                        value: 'id',
                      }"
              placeholder="请选择"
              filterable
              clearable
              multiple
              collapse-tags
              collapse-tags-tooltip
          >
            <template #default="{ item }">
              <span style="margin-right: 8px">{{ item.name }}</span>
              <span style="color: var(--el-text-color-secondary); font-size: 12px" v-if="item.status!=1">离职于<template
                  v-if="item.quit_addtime>0">{{
                  formatDateYmd(item.quit_addtime, false)
                }}</template></span>
            </template>

          </el-select-v2>
        </MyFormItem>
      </el-form-item>
    </el-col>

    <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
      <el-form-item prop="name">
        <MyFormItem title="预约类型" size="large">
          <div style="display: flex;justify-content: flex-end;width: 100%;padding-right: 3px">
            <el-radio-group v-model="searchFormData.cus_type" size="small">
              <el-radio-button label="全部" value=""/>
              <el-radio-button label="新客" value="1"/>
              <el-radio-button label="老客" value="2"/>
            </el-radio-group>
          </div>
        </MyFormItem>
      </el-form-item>
    </el-col>
    <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
      <el-form-item prop="name">
        <MyFormItem title="性别" size="large">
          <div style="display: flex;justify-content: flex-end;width: 100%;padding-right: 3px">
            <el-radio-group v-model="searchFormData.sex" size="small">
              <el-radio-button label="全部" value=""/>
              <el-radio-button label="女" value="2"/>
              <el-radio-button label="男" value="1"/>
              <el-radio-button label="未知" value="0"/>
            </el-radio-group>
          </div>
        </MyFormItem>
      </el-form-item>
    </el-col>
    <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
      <el-form-item prop="name">

        <MyFormItem title="是否待定" size="large">
          <div style="display: flex;justify-content: flex-end;width: 100%;padding-right: 3px">
            <el-radio-group v-model="searchFormData.is_undetermined" size="small">
              <el-radio-button label="是" :value="1"/>
              <el-radio-button label="否" :value="2"/>
            </el-radio-group>
          </div>
        </MyFormItem>

      </el-form-item>
    </el-col>
    <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
      <el-form-item prop="name">
        <MyFormItem :title="searchFormData.is_undetermined==1?'加微日期':'预约日期'" size="large">
          <el-date-picker
              format="YY-MM-DD"
              value-format="YYYY-MM-DD"
              :clearable="false"
              :prefix-icon="customPrefix"
              v-model="searchFormData.date"
              type="daterange"
              :editable="false"
              unlink-panels
              start-placeholder="开始日期"
              end-placeholder="结束日期"
          />
        </MyFormItem>
      </el-form-item>
    </el-col>
    <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
      <el-form-item prop="name">
        <MyFormItem title="预约状态" size="large">
          <el-select
              filterable
              clearable
              v-model="searchFormData.status"
              placeholder="请选择">
            <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </MyFormItem>
      </el-form-item>
    </el-col>
    <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
      <el-form-item prop="name">
        <MyFormItem title="''" size="large" class="no_padding_left">
          <template #prefix>
            <el-select class="quick-search-select" v-model="searchFormData.keyword_type" placeholder="请选择"
                       style="width: 90px;">
              <el-option label="会员ID" value="1"/>
              <el-option label="会员名称" value="2"/>
              <el-option label="会员手机" value="3"/>
            </el-select>
          </template>

          <el-input
              class="quick-search-input"
              v-model="searchFormData.keyword"
              placeholder="请输入搜索内容"
              clearable
              @keydown.enter="onSearchForm"
          >
          </el-input>
        </MyFormItem>

      </el-form-item>
    </el-col>

    <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
      <el-form-item>
        <div class="el-form-submit">
          <el-button type="primary" :icon="Search" @click="onSearchForm"
                     :loading="Props.btLoading">
            搜索
          </el-button>
          <el-button :icon="RefreshLeft" @click="resetSearch">重置</el-button>
        </div>
      </el-form-item>
    </el-col>
  </el-row>
</template>

<style scoped lang="scss">
.el-form-submit {
  display: flex;
  align-items: center;
  height: 40px;
}
</style>